/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.grant.department.impl;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.grant.department.RbacGrantDepartmentPcFuncButtonPermmisionService;
import com.je.rbac.service.permission.GrantMethodEnum;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.permission.template.PcFuncButtonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RbacGrantDepartmentPcFuncButtonPermmisionServiceImpl implements RbacGrantDepartmentPcFuncButtonPermmisionService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private PcFuncButtonService pcFuncButtonService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;

    /**
     * 保存功能按钮权限
     *
     * @param deptId        角色ID
     * @param funcCode      功能按钮
     * @param buttonCodeMap 按钮集合
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveDeptFuncButtonShowPermission(String deptId, String funcCode, Map<String, String> buttonCodeMap, GrantTypeEnum grantType) {
        List<DynaBean> funcButtonPermissionList = new ArrayList<>();
        //如果是排他权限，则设置check或不check，因为他不会受其他影响
        Map<String, String> haveExcludeDeptPermissionMap = new HashMap<>();
        DynaBean eachButtonPermBean;
        for (String eachButtonCode : buttonCodeMap.keySet()) {
            eachButtonPermBean = pcFuncButtonService.writePcFuncButtonShowPermission(funcCode, eachButtonCode, true);
            if (!Strings.isNullOrEmpty(buttonCodeMap.get(eachButtonCode))) {
                if ("0".equals(buttonCodeMap.get(eachButtonCode)) || "false".equals(buttonCodeMap.get(eachButtonCode))) {
                    haveExcludeDeptPermissionMap.put(eachButtonPermBean.getStr("JE_RBAC_PERM_ID"), "1");
                } else {
                    haveExcludeDeptPermissionMap.put(eachButtonPermBean.getStr("JE_RBAC_PERM_ID"), "0");
                }
            }
            funcButtonPermissionList.add(eachButtonPermBean);
        }

        //查找已存在的关联关系
        List<String> permissionIdList = new ArrayList<>();
        for (DynaBean eachPermissionBean : funcButtonPermissionList) {
            permissionIdList.add(eachPermissionBean.getStr("JE_RBAC_PERM_ID"));
        }

        Set<String> extendDeptIdList = rbacDepartmentService.findExtendIds(Lists.newArrayList(deptId));
        extendDeptIdList.add(deptId);

        List<DynaBean> associationList = metaService.select("JE_RBAC_DEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .in("JE_RBAC_DEPARTMENT_ID", extendDeptIdList)
                .in("JE_RBAC_PERM_ID", permissionIdList));
        List<String> havedDeptPermissionList = new ArrayList<>();
        for (DynaBean eachAssociationBean : associationList) {
            if ("0".equals(eachAssociationBean.getStr("DEPTPERM_EXCLUDE_CODE"))
                    && haveExcludeDeptPermissionMap.containsKey(eachAssociationBean.getStr("JE_RBAC_PERM_ID"))) {
                haveExcludeDeptPermissionMap.remove(eachAssociationBean.getStr("JE_RBAC_PERM_ID"));
            }
            havedDeptPermissionList.add(eachAssociationBean.getStr("JE_RBAC_PERM_ID"));
        }

        //写入关联关系
        DynaBean rolePermBean;
        for (DynaBean eachPermissionBean : funcButtonPermissionList) {
            //如果已包含从关联关系，则不做任何操作
            if (havedDeptPermissionList.contains(eachPermissionBean.getStr("JE_RBAC_PERM_ID"))) {
                if (haveExcludeDeptPermissionMap.containsKey(eachPermissionBean.getStr("JE_RBAC_PERM_ID"))) {
                    metaService.executeSql("UPDATE JE_RBAC_DEPTPERM SET DEPTPERM_NOT_CHECKED = {0} WHERE JE_RBAC_DEPARTMENT_ID={1} AND JE_RBAC_PERM_ID={2}",
                            haveExcludeDeptPermissionMap.get(eachPermissionBean.getStr("JE_RBAC_PERM_ID")),
                            deptId,
                            eachPermissionBean.getStr("JE_RBAC_PERM_ID"));
                }
                continue;
            }
            rolePermBean = new DynaBean("JE_RBAC_DEPTPERM", false);
            rolePermBean.set("JE_RBAC_DEPARTMENT_ID", deptId);
            rolePermBean.set("JE_RBAC_PERM_ID", eachPermissionBean.getStr("JE_RBAC_PERM_ID"));

            //设置是否排他权限，只有按钮展示包含排他权限
            rolePermBean.set("DEPTPERM_EXCLUDE_CODE", "0");
            rolePermBean.set("DEPTPERM_EXCLUDE_NAME", "否");
            //授权方式
            rolePermBean.set("DEPTPERM_TYPE_CODE", GrantMethodEnum.ROLE.name());
            rolePermBean.set("DEPTPERM_TYPE_NAME", GrantMethodEnum.ROLE.getDesc());
            //授权类型
            rolePermBean.set("DEPTPERM_GRANTTYPE_CODE", grantType.name());
            rolePermBean.set("DEPTPERM_GRANTTYPE_NAME", grantType.getDesc());
            //todo 设置租户信息
            commonService.buildModelCreateInfo(rolePermBean);
            metaService.insert(rolePermBean);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void removeDeptFuncButtonPermission(String deptId, List<String> buttonPermIdList, GrantTypeEnum grantType) {
        metaService.delete("JE_RBAC_DEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .eq("JE_RBAC_DEPARTMENT_ID", deptId)
                .in("JE_RBAC_DEPTPERM_ID", buttonPermIdList));
    }

}
